import axios from "axios";
// import qs from "qs";
import { Message } from "view-design";
import NProgress from "nprogress";
// import router from '@/router';
import store from "@/store/index";
// import config2 from "../../private.config";
import token from "@/utils/token";
import storage from "@/utils/storage.js";
import { changelocation } from '@/utils/location.js';

import { refreshToken } from "@/api/bidding";

// API 服务器地址
const publicPath =
  process.env.NODE_ENV === "development"
    ? config2.baseUrl.dev
    : config2.baseUrl.pro;
// 上传图片地址
const uploadPath =
  process.env.NODE_ENV === "development"
    ? config2.uploadUrl.dev
    : config2.uploadUrl.pro;

// axios 默认配置
axios.defaults.timeout = 60000;
axios.defaults.headers.common["X-Requested-With"] = "XMLHttpRequest";
axios.defaults.headers.post["Content-Type"] = "application/json";

// 刷新token
function getRefreshToken() {
  const tokenInfo = token.getRT("refreshToken");
  return refreshToken(`refreshToken=${tokenInfo}`);
}

// 是否正在刷新的标记
let isRefreshing = false;
// 重试队列，每一项将是一个待执行的函数形式
let requests = [];

// 请求时的拦截器
axios.interceptors.request.use(
  async (config) => {
    // 这里可以加一些动作, 比如来个进度条开始动作
    NProgress.start();
    // 获取token过期时间
    // const tokenInfo = token.getRT("expiration");
    // if (tokenInfo && !isRefreshing) {
    //   token.setRTByKey("expiration", 1625136651000);
    //   console.log("没有过期手动设置过期");
    // }
    let expiration = token.getRT("expiration");
    let currentTime = new Date().getTime();
    const maxExpirationTime = 30 * 60 * 1000; // 距离过期前30分钟开始获取token
    if (expiration - currentTime > 0) {
      if (expiration > 0 && expiration - currentTime <= maxExpirationTime) {
        if (config.url !== "/web/refreshToken" && !isRefreshing) {
          isRefreshing = true;
          getRefreshToken().then((res) => {
            const { code, data } = res;
            if (code === 200) {
              requests.forEach((cb) => cb(data.accessToken));
              requests = [];
              store.commit("setToken", data.accessToken);
              token.setRT(data);
              isRefreshing = false;
            }
          });
        } else {
          if (config.url !== "/web/refreshToken") {
            return new Promise((resolve) => {
              // 将resolve放进队列，用一个函数形式来保存，等token刷新后直接执行
              requests.push((newToken) => {
                config.headers["Authorization"] = "bearer " + newToken;
                resolve(config);
              });
            });
          }
        }
      }
    }

    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 请求完成后的拦截器
axios.interceptors.response.use(
  (response) => response,
  (error) => {
    // 这里我们把错误信息捕捉, 后面就不需要写 catch 了
    return Promise.resolve(error.response);
  }
);

// 检查状态码
function checkStatus(response) {
  NProgress.done();
  // 如果 http 状态码正常, 则直接返回数据
  if (response.status === 200) {
    // 这里, 如果不需要除 data 外的其他数据, 可以直接 return response.data, 这样可以让后面的代码精简一些
    if (response.data.result === true) {
      // return {
      //   code: response.data.code,
      //   data: response.data.data,
      // };
      return response.data;
    } else {
      return {
        code: response.data.code,
        data: response.data.data,
        message: response.data.message,
      };
    }
  }
  // 异常状态下, 把错误信息返回去
  return {
    code: response.status,
    data: response.statusText,
  };
}

var readyReflesh = false;
// 处理来自后端的错误
async function checkCode(res, errType) {
  if (res.code === 3004 || res.code === 401 || res.code === 3002) {
    if (readyReflesh) return res;
    readyReflesh = true;
    // token.set("");
    // token.setRT("");
    token.remove();
    const data = {
      accessToken: '',
      refreshToken: '',
      tokenType: 'bearer',
      expiration: 0,
      expiresIn: 0
    };
    store.commit('setToken', data);
    Message.warning("登录过期，请重新登录！");
    if (storage.getLoginSource() === 1) {
      setTimeout(() => {
        // window.location.href = window.location.href.split("?")[0];
        window.location.href = changelocation('/login')+ '?returnUrl=' + '/';
        // window.location.href = "https://www.190.vip/login";
      }, 1000);
    } else {
      setTimeout(() => {
        // window.location.reload();
        window.location.href = changelocation('/login')+ '?returnUrl=' + window.location.pathname;
      }, 1000);
    }

    return res;
  }
  if (errType !== "noProcssing") {
    // 需要处理
    if (!res.result) {
      // 默认 toast 显示错误信息，若type为MessageBox，则使用MessageBox
      const err = `${res.message}！`;
      if (errType === "MessageBox") {
        Message.error(err);
      } else {
        console.log(err);
      }
    }
  }
  return res;
}

export function request(obj, needToken, errType, urlencoded) {
  obj.baseURL = publicPath;
  if (needToken && token.get())
    obj.headers = {
      Authorization: "bearer " + token.get().accessToken,
    };
  if (urlencoded) {
    obj.headers["Content-type"] =
      "application/x-www-form-urlencoded;charset=utf-8";
  }
  return axios(obj)
    .then(checkStatus)
    .then((res) => {
      return checkCode(res, errType);
    });
}

export function uploadImage(file) {
  return axios["post"](uploadPath + "/common/upload", qs.stringify(file))
    .then(checkStatus)
    .then((res) => {
      return checkCode(res, errType);
    });
}
export function getImage(obj, needToken) {
  obj.baseURL = publicPath;
  if (needToken && token.get())
    obj.headers = {
      Authorization: "bearer " + token.get().accessToken,
    };
  return axios(obj);
}


